import { Message } from "element-ui";
import cubeCategory from "../../config/cubeDataCategories";

export default class CubeData {
    cubeMsg = {
        HEAD: {
            tag: "MESG",
            version: 65537,
            record_type: "",
            record_subtype: "",
            flow: 0,
            record_num: 0,
            expand_num: 0,
            nonce: ""
        },
        RECORD: [],
        EXPAND: []
    }

    /**
     * 构造函数
     * 发送时创建消息对象：type、subtype有明确的指定
     * 接收时创建消息对象：type、subtype使用默认null，接收后添加
     * @param {消息主类型} type 
     * @param {消息子类型} subtype 
     */
    constructor(type = null, subtype = null){
        this.cubeMsg.HEAD.record_type = type;
        this.cubeMsg.HEAD.record_subtype = subtype;
    }

    /**
     * Send message.
     */
    
    /**
     * 添加记录项(record)
     * @param {字符数组} record 
     * @returns bool
     */
    addRecord(record){
        this.cubeMsg.RECORD[this.cubeMsg.HEAD.record_num++] = record;
        if(this.cubeMsg.RECORD[this.cubeMsg.HEAD.record_num]){
            return true;
        }
        return false;
    }

    /**
     * 添加扩展项(expand)
     * @param {字符数组} expand 
     * @returns bool
     */
    addExpand(expand){
        this.cubeMsg.EXPAND[this.cubeMsg.HEAD.expand_num] = expand;
        if(this.cubeMsg.EXPAND[this.cubeMsg.HEAD.expand_num]){
            return true;
        }
        return false;
    }

    outputJson(){
        return this.cubeMsg;
    }

    /**
     * Receive message.
     */
    recvMessage(msg){
        let obj = JSON.parse(msg);
        console.log(obj);
        this.cubeMsg.HEAD = obj.HEAD;
        console.log(this.cubeMsg.HEAD);
        this.cubeMsg.RECORD = obj.RECORD;
        this.cubeMsg.EXPAND = obj.EXPAND;
    }

    /**
     * 处理发来的CUBE消息，返回该CUBE消息的type与subtype，便于后续根据type与subtype执行相应方法.
     * @param {CUBE消息} msg 
     * @returns CUBE消息类型子类型
     */
    verifyMessage(msg){
        this.recvMessage(msg);
        let type = this.cubeMsg.HEAD.record_type;
        let subtype = this.cubeMsg.HEAD.record_subtype;
        console.log({type,subtype});
        if(cubeCategory.TYPE.includes(type) && cubeCategory.SUBTYPE.includes(subtype)){
            return {type, subtype};
        }
        Message.error('不支持该CUBE消息的类型/子类型或消息格式有误');
        return false;
    }
}